import fetch from 'dva/fetch';
import { getToken } from './common';

function parseJSON(response) {
  return response.json();
}

function checkStatus(response, callback) {
  // if (response.status >= 200 && response.status < 300) {
  //   return response;
  // }
  if (response.status == 401) {
    const error = new Error('clear');
    error['response'] = response;
    error['callback'] = callback;
    throw error;
  }
  return response;
}

function checkSuccess(data, callback) {
  if (data.success === true) {
    return data.result;
  }
  else {
    const error = new Error(data.error.message);
    error['response'] = data.error.details;
    error['callback'] = callback;
    throw error;
  }
}

/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export default function request({ url, options }, callback?) {
  options.headers = Object.assign({}, options.headers, getToken());
  return fetch(url, options)
    .then(res => checkStatus(res, callback))
    .then(parseJSON)
    .then(data => checkSuccess(data, callback))
    .then(data => (data))
  //.catch(err => ({ err }));
}
